package com.vehicle.biz.Impl;

import cn.hutool.core.util.IdUtil;
import com.vehicle.biz.SystemConfigBiz;
import com.vehicle.domains.entity.SysModifyRecordEntity;
import com.vehicle.domains.entity.SystemConfigEntity;
import com.vehicle.domains.info.UserInfo;
import com.vehicle.domains.vo.req.systemConfig.UpdateSystemConfigReq;
import com.vehicle.service.SysModifyRecordService;
import com.vehicle.service.config.SystemConfigService;
import com.vehicle.threadLocal.UserContextThreadLocal;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SystemConfigBizImpl implements SystemConfigBiz {
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private SysModifyRecordService sysModifyRecordService;

    public void updateSystemConfig(UpdateSystemConfigReq  req) {
        //先检查是否存在配置
        SystemConfigEntity systemConfigEntity = systemConfigService.selectByKey(req.getKey());
        String beforeValue = systemConfigEntity == null ? "" : systemConfigEntity.getValue();
        String afterValue= req.getValue();
        if (systemConfigEntity == null) {
            systemConfigEntity = new SystemConfigEntity();
            BeanUtils.copyProperties(req, systemConfigEntity);
            systemConfigService.insert(systemConfigEntity);
        } else {
            SystemConfigEntity updateSystemConfigEntity = new SystemConfigEntity();
            BeanUtils.copyProperties(req, updateSystemConfigEntity);
            systemConfigService.updateByKey(updateSystemConfigEntity);
        }
        systemConfigService.removeCache(req.getKey());

        SysModifyRecordEntity sysModifyRecordEntity = new SysModifyRecordEntity();
        sysModifyRecordEntity.setBatchNo(IdUtil.simpleUUID());
        sysModifyRecordEntity.setBeforeValue(beforeValue);
        sysModifyRecordEntity.setAfterValue(afterValue);
        sysModifyRecordEntity.setModifyType("system_config.v");
        UserInfo userInfo = UserContextThreadLocal.getUserInfo();
        sysModifyRecordEntity.setUserId(userInfo.getId());
        try {
            sysModifyRecordService.addRecord(sysModifyRecordEntity);
        } catch (Exception e) {
            log.error("变更信息记录异常", e);
        }
    }
}
